<template>
  <el-card class="search-panel">
    <el-form
      class="search-form"
      ref="searchFormRef"
      size="small"
      :label-width="config.labelWidth"
      :model="searchForm"
      inline
    >
      <el-row>
        <el-col>
          <template v-for="item in config.formItems" :key="item.field">
            <el-form-item :label="config.showLabel ? item.label : ''" :prop="item.field">
              <template v-if="item.type === 'input'">
                <el-input v-model="searchForm[item.field]" :placeholder="item.placeholder" clearable />
              </template>
              <template v-else-if="item.type === 'select'">
                <el-select v-model="searchForm[item.field]" :placeholder="item.placeholder" clearable>
                  <el-option
                    :label="option.label"
                    :value="option.value"
                    v-for="option in item.optionsGetter && item.optionsGetter.length
                      ? $store.getters[item.optionsGetter]
                      : item.options"
                    :key="option.label"
                  />
                </el-select>
              </template>
            </el-form-item>
          </template>
          <el-form-item>
            <slot name="button">
              <el-button type="primary" @click="handleQuery"><i class="el-icon-search"></i> 查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </slot>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
</template>

<script lang="ts">
import { defineComponent, PropType, ref, watch } from 'vue'
import { SearchConfig } from './types'
import { ElForm } from 'element-plus'

export default defineComponent({
  name: 'SearchPanel',
  props: {
    modelValue: {
      type: Object,
      default: () => ({})
    },
    config: {
      type: Object as PropType<SearchConfig>,
      required: true
    }
  },
  emits: ['query', 'reset', 'update:modelValue'],
  setup(props, { emit }) {
    const searchForm = ref({ ...props.modelValue })
    const searchFormRef = ref<InstanceType<typeof ElForm>>()

    watch(
      searchForm,
      (newValue) => {
        emit('update:modelValue', newValue)
      },
      { deep: true }
    )

    const handleQuery = () => {
      emit('query')
    }

    const handleReset = () => {
      emit('reset')
    }

    const resetFields = () => {
      searchFormRef.value?.resetFields()
    }

    return { searchForm, searchFormRef, handleQuery, handleReset, resetFields }
  }
})
</script>

<style lang="less" scoped>
.search-panel {
  margin-bottom: 20px;
}
.search-form {
  .el-form-item {
    margin: 6px 10px 6px 0;
  }
}
</style>
